clear
clear mata
clear matrix
set maxvar 10000
estimates clear

loc events "wneg2 any_rlost_job male_rwidowed fem_rwidowed any_rhosp any_disab any_health3to5 any_rcancr any_rstrok any_rcardiac any_rmemory"

//Estout setup
loc NOMEAN_estout "cells(b(fmt(3) star) se(par fmt(3))) mlabels(none) la collabels(,none) eqlabels(none) varwidth(16) modelwidth(12) style(tex) starl(* 0.05 ** .01) rep" 
loc NOMEAN2_estout "stats( Observations Households, fmt(0 0)) cells(b(fmt(3) star) se(par fmt(3))) mlabels(none) la collabels(,none) eqlabels(none) varwidth(16) modelwidth(12) style(tex) starl(* 0.05 ** .01) rep" 
loc Mech_estout "cells(b(fmt(2) star) se(par fmt(2))) mlabels(none) la collabels(,none) eqlabels(none) varwidth(16) modelwidth(12) style(tex) starl(* 0.05 ** .01) rep" 
loc Mech_estout2 "stats( Observations Households, fmt(0 0)) cells(b(fmt(2) star) se(par fmt(2))) mlabels(none) la collabels(,none) eqlabels(none) varwidth(16) modelwidth(12) style(tex) starl(* 0.05 ** .01) rep"

/**************************************************/
/**************************************************/
/**************************************************/
/* Summary Statistics and Pooled Regressions*/
/**************************************************/
/**************************************************/
/**************************************************/
/* Load analysis file */
use data/constructed_data/analysisdata.dta, clear

local sumvars oldest_age any_nonwhite highest_ed real_hitot_pc real_hatota_pc rbeq100 any_work rownhm any_ssi ///
	any_rhosp any_disability any_bad_health oop rliv75 single_male single_female nkids2 any_lvtenmi
	
//Table 1 -- I don't think this is used anymore?
estimates clear
eststo full: quietly estpost summarize `sumvars' [weight = weight]
eststo ptok: quietly estpost summarize `sumvars' [weight = weight] if at_pk==1
eststo ktop: quietly estpost summarize `sumvars' [weight = weight] if at_kp==1
eststo help: quietly estpost summarize `sumvars' [weight = weight] if any_helpr==1
esttab full ptok ktop help using output/misc_tables/sumstats.tex, style(tex) la posthead("") collabels(,none) ///
	mlabels(,none) frag nonum rep cells("mean(label(Mean) pattern(1 1 1 1 1) fmt(2))") 

	
//Table 2 -- I think this is now Table 1
estimates clear
eststo full: quietly estpost summarize at_pk amt_pk_pos at_kp amt_kp_pos rbeq100 any_helpr help_hrs_pos [weight = weight]
eststo work: quietly estpost summarize at_pk amt_pk_pos at_kp amt_kp_pos rbeq100 any_helpr help_hrs_pos [weight = weight] if any_work==1
eststo loww: quietly estpost summarize at_pk amt_pk_pos at_kp amt_kp_pos rbeq100 any_helpr help_hrs_pos [weight = weight] if wealth_quintile_pc==1
eststo highw: quietly estpost summarize at_pk amt_pk_pos at_kp amt_kp_pos rbeq100 any_helpr help_hrs_pos [weight = weight] if wealth_quintile_pc==5
eststo young: quietly estpost summarize at_pk amt_pk_pos at_kp amt_kp_pos rbeq100 any_helpr help_hrs_pos [weight = weight] if oldest_age<=60
eststo old: quietly estpost summarize at_pk amt_pk_pos at_kp amt_kp_pos rbeq100 any_helpr help_hrs_pos [weight = weight] if oldest_age>=75
eststo poorh: quietly estpost summarize at_pk amt_pk_pos at_kp amt_kp_pos rbeq100 any_helpr help_hrs_pos [weight = weight] if rshlt==5
eststo exch: quietly estpost summarize at_pk amt_pk_pos at_kp amt_kp_pos rbeq100 any_helpr help_hrs_pos [weight = weight] if rshlt==1
eststo dis: quietly estpost summarize at_pk amt_pk_pos at_kp amt_kp_pos rbeq100 any_helpr  help_hrs_pos  [weight = weight] if any_disability==1
eststo sf: quietly estpost summarize at_pk amt_pk_pos at_kp amt_kp_pos rbeq100 any_helpr help_hrs_pos [weight = weight] if single_female==1
eststo sm: quietly estpost summarize at_pk amt_pk_pos at_kp amt_kp_pos rbeq100 any_helpr help_hrs_pos [weight = weight] if single_male==1
eststo co: quietly estpost summarize at_pk amt_pk_pos at_kp amt_kp_pos rbeq100 any_helpr help_hrs_pos [weight = weight] if (single_female!=1 & single_male!=1)

esttab full old young loww highw work  using output/table1/sumstats_grp1.tex, style(tex) la posthead("") collabels(,none) ///
	mlabels(,none) frag nonum rep cells("mean(label(Mean) pattern(1 1 1 1 1) fmt(2))") 
	
esttab sf sm co poorh exch dis using output/table1/sumstats_grp2.tex, style(tex) la posthead("") collabels(,none) ///
	mlabels(,none) frag nonum rep cells("mean(label(Mean) pattern(1 1 1 1 1) fmt(2))") 

	
// Table ?? -- Event Frequencies; This is not used, put in misc folder
preserve
collapse (max) `events' weight, by(hhidpn)
estimates clear
eststo full: quietly estpost summarize `events' [weight = weight]
esttab full using output/misc_tables/events.tex, style(tex) la posthead("") collabels(,none) ///
	mlabels(,none) frag nonum rep cells("mean(label(Mean) pattern(1 1) fmt(2))") 
restore

//Figure ?? -- Bar Graphs Showing Frequencies; This is not used, put in misc folder
preserve
keep if hhwaves==10 | hhwaves==11 /*Only households in every wave*/
xtset hhidpn wave
xtdescribe

bysort hhidpn: egen pkwaves = sum(at_pk)
bysort hhidpn: egen kpwaves = sum(at_kp)
bysort hhidpn: egen helpwaves = sum(any_helpr)

collapse (mean) pkwaves kpwaves helpwaves, by(hhidpn)
tab pkwaves if pkwaves>0
tab kpwaves if kpwaves>0
tab helpwaves if helpwaves>0

gen nopk = pkwaves==0
gen nokp = kpwaves==0
gen nohelp = helpwaves==0
su no*

count 

graph bar if pkwaves>0, over(pkwaves, label(labsize(huge))) ylabel(0(10)50, labsize(huge)) title("Parent to Child Transfers", size(huge)) ///
	graphregion(color(white)) ytitle("Percent", size(huge))
graph export output/misc_figures/pk_freq_n0.pdf, replace

graph bar if kpwaves>0, over(kpwaves, label(labsize(huge))) ylabel(0(10)50, labsize(huge)) title("Child to Parent Transfers", size(huge)) ///
	graphregion(color(white)) ytitle("Percent", size(huge))
graph export output/misc_figures/kp_freq_n0.pdf, replace

graph bar if helpwaves>0, over(helpwaves, label(labsize(huge))) ylabel(0(10)50, labsize(huge)) title("Child Helping Parent(s)", size(huge)) ///
	graphregion(color(white)) ytitle("Percent", size(huge))
graph export output/misc_figures/help_freq_n0.pdf, replace

restore

// Table B1 Pooled Regressions
local regvars ln_wealth ln_inc any_work single_male single_female any_rhosp any_disability any_bad_health any_nonwhite hsgrad college 
local outvars ln_wealth ln_inc any_work single_male single_female any_rhosp any_disability any_bad_health

estimates clear
eststo pk_cs: reg at_pk `regvars' i.kidcat oldest_age oldest_age2 i.wave [pweight = weight], cluster(hhidpn)
eststo kp_cs: reg at_kp `regvars' i.kidcat oldest_age oldest_age2 i.wave [pweight = weight], cluster(hhidpn)
eststo hp_cs: reg any_helpr `regvars' i.kidcat oldest_age oldest_age2 i.wave [pweight = weight], cluster(hhidpn)
eststo pk_fe: xtreg at_pk `regvars' i.kidcat oldest_age oldest_age2 i.wave [pweight = weight], fe cluster(hhidpn)
eststo kp_fe: xtreg at_kp `regvars' i.kidcat oldest_age oldest_age2 i.wave [pweight = weight], fe cluster(hhidpn)
eststo hp_fe: xtreg any_helpr `regvars' i.kidcat oldest_age oldest_age2 i.wave [pweight = weight], fe cluster(hhidpn)

estout pk_cs pk_fe kp_cs kp_fe hp_cs hp_fe using output/tableb1/CS_FE.tex,`NOMEAN_estout' keep(`outvars')








//***********************************//
//***********************************//
//***********Great Recession Graphs***************//
//***********************************//
//***********************************//
clear
estimates clear

//load main analysis file
use data/constructed_data/analysisdata.dta if wave >=2, clear
/* subset to only one row per HH */
bys hhid_group wave: gen dup = cond(_N == 1, 0, _n - 1)
keep if kapick > .5 //  keep if kapick more than half the time

xtset hhidpn wave 
/* make weight */
cap drop weight
bysort hhidpn: egen weight = mean(rwthh)
drop if weight==0 


/*Wealth shocks*/
/* Make positive wealth shock */
gen wpos = (real_hatota > 1.5*l.real_hatota) & l.real_hatota>20000 & l.real_hatota!=.
gen wneg = (real_hatota < .75*l.real_hatota) & l.real_hatota>20000 & l.real_hatota!=. 

/* remake welath shock  */
cap drop wneg2
gen wneg2 = wneg
replace wneg2 = 0 if l.wpos==1
replace wneg2 = 0 if l2.wpos==1

gen wpos2 = wpos
replace wpos2 = 0 if l.wneg==1
replace wpos2 = 0 if l2.wneg==1

/* rename avg_real_ktcamt amt_pk
rename avg_real_kfcamt amt_kp */

egen avg_lifetime_wealth_pc = mean(real_hatota_pc), by(hhidpn)
xtile wealthpctile_pc = avg_lifetime_wealth_pc, nq(2)

/* subset to time period around GR (wave 10) */
keep if wave>=7 & wave<=12 & oldest_age>=50 & oldest_age<=85


foreach n of varlist wneg2  {
    preserve

    /* create respondent-level dummy for ever wealth shock */
    bys hhidpn: egen `n'ever = max(`n')
    *keep if `n'ever==1
    /* create dummy for whether wealth shock is in wave 10 */
    gen `n'10 = `n'==1 & wave==10 
    /* create a table of wealth shock in wave 10 */
    tab `n'10 if wave==10
    /* creat a respondent level dummy for ever having wealth shock inwave 10 (treated) */
    bysort hhidpn: egen `n'10ever = max(`n'10)
    /* Create indicator for whetehr it's wave 10 */
    gen wave10 = wave==10
    /* Create respondent-level indicator for whether ever at wave 10 */
    bysort hhidpn: egen w10ever = max(wave10)
    /* Restrict to only those who reach wave 10 */
    keep if w10ever==1
    /* Calculate the means of the outcome in each wave by treatment */
    collapse (mean) at_pk at_kp any_helpr [w=weight], by(wave `n'10ever)
    /* Make it wide by treatment */
    reshape wide at_pk at_kp any_helpr, i(wave) j(`n'10ever)
    /* for each outcome-treatment column */
    foreach z of varlist at_pk* at_kp* {
        /* get mean  at wave 8*/
        su `z' if wave==8
        scalar temp = r(mean)
        /* calcualte difference between wave value and wave 8 value */
        /* this provides the graphing data */
        gen `z'2 = `z' - temp
    }
    /* calculate the difference between treat and control values */
    gen diff_10_at_pk = at_pk12 - at_pk02
    gen diff_10_at_kp = at_kp12 - at_kp02

    /* extract needed values to local macro */
    /* the summary works because only 1 obs so mean == the value */
    /* not sure how how else to get the right val that's not sensitive to reordering */
    su at_pk1 if wave == 8
    local wave8_atpk1 = round(r(mean), .001)
    su diff_10_at_pk if wave == 10
    local wave10_diff_atpk = round(r(mean), .001)
    su at_kp1 if wave == 8
    local wave8_atkp1 = round(r(mean), .001)
    su diff_10_at_kp if wave == 10
    local wave10_diff_atkp = round(r(mean), .001)

    /* Create figures */
    twoway line at_pk02 wave, lcolor(gray)  || line at_pk12 wave, lwidth(medthick) lcolor(black) xline(9.5, lcolor(black) lpattern(dash)) ///
        graphregion(color(white)) ylabel(-0.1(0.05)0.05, labsize(vlarge)) xlabel(, labsize(vlarge)) legend(lab(2 "Wave 10 Shock") lab(1 "No Wave 10 Shock")) ///
        xtitle("HRS Wave", size(vlarge)) ytitle(, size(vlarge)) title("Parent to Child Transfer", size(vlarge)) yline(0, lcolor(gs12))  text(0.03 11 "Wave 10 Gap: `wave10_diff_atpk'" 0.04 11 "Wave 8 Treated Mean: `wave8_atpk1'")
    graph export "output/figure1/`n'10_at_pk.pdf", replace

    twoway line at_kp02 wave, lcolor(gray)  || line at_kp12 wave, lwidth(medthick) lcolor(black) xline(9.5, lcolor(black) lpattern(dash)) ///
        graphregion(color(white)) ylabel(-0.05(0.05)0.05, labsize(vlarge)) xlabel(, labsize(vlarge)) legend(lab(2 "Wave 10 Shock") lab(1 "No Wave 10 Shock")) ///
        xtitle("HRS Wave", size(vlarge)) ytitle(, size(vlarge)) title("Child to Parent Transfer", size(vlarge)) yline(0, lcolor(gs12))  text(0.03 11 "Wave 10 Gap: `wave10_diff_atkp'" 0.037 11 "Wave 8 Treated Mean: `wave8_atkp1'")
    graph export "output/figure1/`n'10_at_kp.pdf", replace

    /* save the data file to be able to fill in the values on graph */
    save output/figure1/`n'_grmeans, replace
    restore
}

foreach n of varlist any_rlost_job {
    preserve

    /* create respondent-level dummy for ever event */
    bys hhidpn: egen `n'ever = max(`n')
    *keep if `n'ever==1
    /* create dummy for whether event is in wave 10 */
    gen `n'10 = `n'==1 & wave==10 
    /* create a table of event in wave 10 */
    tab `n'10 if wave==10
    /* creat a respondent level dummy for ever having wealth shock inwave 10 (treated) */
    bysort hhidpn: egen `n'10ever = max(`n'10)
    /* Create indicator for whetehr it's wave 10 */
    gen wave10 = wave==10
    /* Create respondent-level indicator for whether ever at wave 10 */
    bysort hhidpn: egen w10ever = max(wave10)
    /* Restrict to only those who reach wave 10 */
    keep if w10ever==1
    /* Calculate the means of the outcome in each wave by treatment */
    collapse (mean) at_pk at_kp any_helpr [w=weight], by(wave `n'10ever)
    /* Make it wide by treatment */
    reshape wide at_pk at_kp any_helpr, i(wave) j(`n'10ever)
    /* for each outcome-treatment column */
    foreach z of varlist at_pk* at_kp* {
        /* get mean  at wave 8*/
        su `z' if wave==8
        scalar temp = r(mean)
        /* calcualte difference between wave value and wave 8 value */
        /* this provides the graphing data */
        gen `z'2 = `z' - temp
    }
    /* calculate the difference between treat and control values */
    gen diff_10_at_pk = at_pk12 - at_pk02
    gen diff_10_at_kp = at_kp12 - at_kp02

    /* extract needed values to local macro */
    /* the summary works because only 1 obs so mean == the value */
    /* not sure how how else to get the right val that's not sensitive to reordering */
    su at_pk1 if wave == 8
    local wave8_atpk1 = round(r(mean), .001)
    su diff_10_at_pk if wave == 10
    local wave10_diff_atpk = round(r(mean), .001)
    su at_kp1 if wave == 8
    local wave8_atkp1 = round(r(mean), .001)
    su diff_10_at_kp if wave == 10
    local wave10_diff_atkp = round(r(mean), .001)

    twoway line at_pk02 wave, lcolor(gray)  || line at_pk12 wave, lwidth(medthick) lcolor(black) xline(9.5, lcolor(black) lpattern(dash)) ///
        graphregion(color(white)) ylabel(-0.1(0.05)0.05, labsize(vlarge)) xlabel(, labsize(vlarge)) legend(lab(2 "Wave 10 Shock") lab(1 "No Wave 10 Shock")) ///
        xtitle("HRS Wave", size(vlarge)) ytitle(, size(vlarge)) title("Parent to Child Transfer", size(vlarge)) yline(0, lcolor(gs12))  text(0.03 11 "Wave 10 Gap: `wave10_diff_atpk'" 0.04 11 "Wave 8 Treated Mean: `wave8_atpk1'")
    graph export "output/figure1/`n'10_at_pk.pdf", replace

    twoway line at_kp02 wave, lcolor(gray)  || line at_kp12 wave, lwidth(medthick) lcolor(black) xline(9.5, lcolor(black) lpattern(dash)) ///
        graphregion(color(white)) ylabel(-0.05(0.05)0.05, labsize(vlarge)) xlabel(, labsize(vlarge)) legend(lab(2 "Wave 10 Shock") lab(1 "No Wave 10 Shock")) ///
        xtitle("HRS Wave", size(vlarge)) ytitle(, size(vlarge)) title("Child to Parent Transfer", size(vlarge)) yline(0, lcolor(gs12))  text(0.03 11 "Wave 10 Gap: `wave10_diff_atkp'" 0.037 11 "Wave 8 Treated Mean: `wave8_atkp1'")
    graph export "output/figure1/`n'10_at_kp.pdf", replace
    
    save output/figure1/`n'_grmeans, replace
    restore
}






//***********************************//
//***********************************//
//***********Event Study Regressions************//
//***********************************//
//***********************************//
/* These are for figures 2-4 and figure 7 as well as table 2-5  */

use data/constructed_data/analysisdata.dta, clear
foreach event in any_health3to5 any_rcancr any_rstrok any_rcardiac any_rmemory wneg2 any_rlost_job any_rhosp any_disab  { 
    di "`event'"
    preserve

    //Setup
    gen temp = 1 if `event'==1 & l.`event'==0 & l2.`event'==0 & any_rwidowed==0 
    bys hhidpn: egen firstevent = min(wave*temp)
    bys hhidpn: egen ageatevent = min(oldest_age*temp)
    drop temp
    gen eventtime = wave - firstevent 
    gen eventever = firstevent~=.
    keep if eventever==1  

    //Pre-event wealth categories
    egen temp1 = mean(real_hatota_pc) if eventtime<0, by(hhidpn)
    bys hhidpn: egen temp2 = min(temp1)
    gen wealthpctile_pc = 1 if temp2<medwealth
    replace wealthpctile_pc = 2 if temp2>=medwealth
    drop temp1 temp2



    //Event indicators
    gen b3m = eventtime<=-3
    gen b2 = eventtime==-2
    gen b1 = eventtime==-1
    gen e0 = eventtime==0
    forvalues l = 1/9 {
    gen a`l' = eventtime==`l'
    }


    /* Get Couple status during event and two waves before the event */
    gen single = single_female == 1 | single_male == 1

    egen single_event = max(single*e0), by(hhidpn)

    /* mark it as 0 if it's 0 in b1 or b2 */

    egen single_b2 = max(single*b2), by(hhidpn)
    egen single_b1 = max(single*b1), by(hhidpn)
    replace single_event = 0 if single_b1 == 0 | single_b2 == 0

    replace wlthpc = wlthpc/1000
    replace incpc = incpc/1000
    replace oop = oop/1000
    rename any_disability adis
    rename any_lvtenmi any_lv10 
    rename nk_lvtenmi nk_lv10
    rename any_live_nrshm any_nh
    rename any_medicaid any_mcd
    rename any_rhomcar any_hcr
    

    //Regressions
    
    foreach lhs of varlist at_pk at_kp any_helpr any_hcr fkh_apk {
        /* Overall */
        qui xtreg `lhs' b3m b2 e0 a1 a2 a3 a4 a5 a6 a7 a8 a9 oldest_age oldest_age2 i.wave [pweight = weight], fe cluster(hhidpn)
        regsave b3m b2 e0 a1 a2 a3  using output/event_study_regsave/`event'_`lhs'.dta, replace ci addlabel(group, full)
        qui estadd scalar Observations = e(N)
        qui estadd scalar Households = e(N_g)
        su `lhs' [weight = weight] if e(sample)==1 & eventtime<0
        qui estadd scalar Mean = r(mean)
        eststo p`lhs'_`event'

        /* Low wealth only */
        qui xtreg `lhs' b3m b2 e0 a1 a2 a3 a4 a5 a6 a7 a8 a9 oldest_age oldest_age2 i.wave [pweight = weight] if wealthpctile_pc==1, fe cluster(hhidpn)
        regsave b3m b2 e0 a1 a2 a3  using output/event_study_regsave/`event'_`lhs'_lw.dta, replace ci addlabel(group, lw)
        qui estadd scalar Observations = e(N)
        qui estadd scalar Households = e(N_g)
        su `lhs' [weight = weight] if e(sample)==1 & eventtime<0
        eststo w1`lhs'_`event'

        /* high wealth only */
        qui xtreg `lhs'  b3m b2 e0 a1 a2 a3 a4 a5 a6 a7 a8 a9 oldest_age oldest_age2 i.wave [pweight = weight] if wealthpctile_pc==2, fe cluster(hhidpn)
        regsave b3m b2 e0 a1 a2 a3  using output/event_study_regsave/`event'_`lhs'_hw.dta, replace ci addlabel(group, hw)
        qui estadd scalar Observations = e(N)
        qui estadd scalar Households = e(N_g)
        su `lhs' [weight = weight] if e(sample)==1 & eventtime<0
        eststo w2`lhs'_`event'

        /* Less than 65 */
        qui xtreg `lhs'  b3m b2 e0 a1 a2 a3 a4 a5 a6 a7 a8 a9 oldest_age oldest_age2 i.wave [pweight = weight] if ageatevent>=55 & ageatevent<=64, fe cluster(hhidpn)
        regsave b3m b2 e0 a1 a2 a3  using output/event_study_regsave/`event'_`lhs'_byage.dta, replace ci addlabel(group, 55_64)

        /* Greater than (or equal to) 65 */
        qui xtreg `lhs'  b3m b2 e0 a1 a2 a3 a4 a5 a6 a7 a8 a9 oldest_age oldest_age2 i.wave [pweight = weight] if ageatevent>=65 & ageatevent<=74, fe cluster(hhidpn)
        regsave b3m b2 e0 a1 a2 a3  using output/event_study_regsave/`event'_`lhs'_byage.dta, append ci addlabel(group, 65_74)

        /* Single HHs */
        qui xtreg `lhs'  b3m b2 e0 a1 a2 a3 a4 a5 a6 a7 a8 a9 oldest_age oldest_age2 i.wave [pweight = weight] if single_event == 1, fe cluster(hhidpn)
        regsave b3m b2 e0 a1 a2 a3  using output/event_study_regsave/`event'_`lhs'_byhhstructure.dta, replace ci addlabel(group, s)
        
        /* Non-single HHs */
        qui xtreg `lhs'  b3m b2 e0 a1 a2 a3 a4 a5 a6 a7 a8 a9 oldest_age oldest_age2 i.wave [pweight = weight] if single_event == 0, fe cluster(hhidpn)
        regsave b3m b2 e0 a1 a2 a3  using output/event_study_regsave/`event'_`lhs'_byhhstructure.dta, append ci addlabel(group, cpl) 
        
    }

    //Regressions - Other tables
    foreach lhs of varlist wlthpc incpc oop rbeq100 rliv75 any_lv10 amt_pk amt_kp help_hrs { 
        qui xtreg `lhs' b3m b2 e0 a1 a2 a3 a4 a5 a6 a7 a8 a9 oldest_age oldest_age2 i.wave [pweight = weight], fe cluster(hhidpn)
        qui estadd scalar Observations = e(N)
        qui estadd scalar Households = e(N_g)
        su `lhs' [weight = weight] if e(sample)==1 & eventtime<0
        eststo p`lhs'_`event'
    }
    restore
}

use data\constructed_data\analysisdata.dta, clear

loc events "any_rwidowed male_rwidowed fem_rwidowed"

foreach event in `events' {
    di "`event'"
    preserve

    //Setup
    gen temp = 1 if `event'==1 & l.`event'==0 & l2.`event'==0
    bys hhidpn: egen firstevent = min(wave*temp)
    bys hhidpn: egen ageatevent = min(oldest_age*temp)
    drop temp
    gen eventtime = wave - firstevent 
    gen eventever = firstevent~=.
    keep if eventever==1  

    //Pre-event wealth categories
    egen temp1 = mean(real_hatota_pc) if eventtime<0, by(hhidpn)
    bys hhidpn: egen temp2 = min(temp1)
    gen wealthpctile_pc = 1 if temp2<medwealth
    replace wealthpctile_pc = 2 if temp2>=medwealth
    drop temp1 temp2


    //Event indicators
    gen b3m = eventtime<=-3
    gen b2 = eventtime==-2
    gen b1 = eventtime==-1
    gen e0 = eventtime==0
    forvalues l = 1/9 {
    gen a`l' = eventtime==`l'
    }

    replace wlthpc = wlthpc/1000
    replace incpc = incpc/1000
    replace oop = oop/1000
    rename any_disability adis
    rename any_lvtenmi any_lv10 
    rename nk_lvtenmi nk_lv10
    rename any_live_nrshm any_nh
    rename any_medicaid any_mcd
    rename female_rhomcar any_hcr


//Regressions - Main table and figures 2-4 and 7, widowhood

    foreach lhs of varlist at_pk at_kp any_helpr any_hcr fkh_apk {
        di "`lhs'"
        qui xtreg `lhs' b3m b2 e0 a1 a2 a3 a4 a5 a6 a7 a8 a9 oldest_age oldest_age2 i.wave [pweight = weight], fe cluster(hhidpn)
        regsave b3m b2 e0 a1 a2 a3  using output/event_study_regsave/`event'_`lhs'.dta, replace ci addlabel(group, full)
        qui estadd scalar Observations = e(N)
        qui estadd scalar Households = e(N_g)
        su `lhs' [weight = weight] if e(sample)==1 & eventtime<0
        qui estadd scalar Mean = r(mean)
        eststo p`lhs'_`event'

        qui xtreg `lhs' b3m b2 e0 a1 a2 a3 a4 a5 a6 a7 a8 a9 oldest_age oldest_age2 i.wave [pweight = weight] if wealthpctile_pc==1, fe cluster(hhidpn)
        regsave b3m b2 e0 a1 a2 a3  using output/event_study_regsave/`event'_`lhs'_lw.dta, replace ci addlabel(group, lw)
        qui estadd scalar Observations = e(N)
        qui estadd scalar Households = e(N_g)
        su `lhs' [weight = weight] if e(sample)==1 & eventtime<0
        eststo w1`lhs'_`event'

        qui xtreg `lhs'  b3m b2 e0 a1 a2 a3 a4 a5 a6 a7 a8 a9 oldest_age oldest_age2 i.wave [pweight = weight] if wealthpctile_pc==2, fe cluster(hhidpn)
        regsave b3m b2 e0 a1 a2 a3  using output/event_study_regsave/`event'_`lhs'_hw.dta, replace ci addlabel(group, hw)
        qui estadd scalar Observations = e(N)
        qui estadd scalar Households = e(N_g)
        su `lhs' [weight = weight] if e(sample)==1 & eventtime<0
        eststo w2`lhs'_`event'


        qui xtreg `lhs'  b3m b2 e0 a1 a2 a3 a4 a5 a6 a7 a8 a9 oldest_age oldest_age2 i.wave [pweight = weight] if ageatevent>=55 & ageatevent<=64, fe cluster(hhidpn)
        regsave b3m b2 e0 a1 a2 a3  using output/event_study_regsave/`event'_`lhs'_byage.dta, replace ci addlabel(group, 55_64)

        qui xtreg `lhs' b3m b2 e0 a1 a2 a3 a4 a5 a6 a7 a8 a9 oldest_age oldest_age2 i.wave [pweight = weight] if ageatevent>=65 & ageatevent<=74, fe cluster(hhidpn)
        regsave b3m b2 e0 a1 a2 a3  using output/event_study_regsave/`event'_`lhs'_byage.dta, append ci addlabel(group, 65_74)

    }

//Regressions - Other tables
    foreach lhs of varlist amt_pk amt_kp help_hrs wlthpc incpc rliv75 rbeq100 oop any_lv10 {
        di "`lhs'"
        qui xtreg `lhs' b3m b2 e0 a1 a2 a3 a4 a5 a6 a7 a8 a9 oldest_age oldest_age2 i.wave [pweight = weight], fe cluster(hhidpn)
        qui estadd scalar Observations = e(N)
        qui estadd scalar Households = e(N_g)
        eststo p`lhs'_`event'
    }

restore
}

//***********************************//
//***********************************//
//*******Main Table Construction*****//
//***********************************//
//***********************************//

cap drop e0 a1
gen e0 = .
gen a1 = .
     label var e0 "Event Wave"
     label var a1 "One Wave After"

//Tables of event estimates in wave of and after event
// Each iteration is a table panel 
foreach lhs in at_pk at_kp {
    /* Table 2 -- main events */
    estout p`lhs'_wneg2 p`lhs'_any_rlost_job  p`lhs'_male_rwidowed p`lhs'_fem_rwidowed p`lhs'_any_rhosp p`lhs'_any_disab p`lhs'_any_health3to5 using output/table2/`lhs'_post.tex, `NOMEAN_estout' keep(e0 a1) 

    /* Table 4 -- main events - low-wealth households */
    estout w1`lhs'_wneg2 w1`lhs'_any_rlost_job w1`lhs'_male_rwidowed w1`lhs'_fem_rwidowed w1`lhs'_any_rhosp w1`lhs'_any_disab w1`lhs'_any_health3to5 using output/table4/`lhs'_post_lw.tex, `NOMEAN_estout' keep(e0 a1) 

    /* Table 5 -- main events - high-wealth households */
    estout w2`lhs'_wneg2 w2`lhs'_any_rlost_job w2`lhs'_male_rwidowed w2`lhs'_fem_rwidowed w2`lhs'_any_rhosp w2`lhs'_any_disab w2`lhs'_any_health3to5 using output/table5/`lhs'_post_hw.tex, `NOMEAN_estout' keep(e0 a1) 

    /* Table 3 --  specific health diagnoses*/
    estout p`lhs'_any_rcardiac p`lhs'_any_rstrok  p`lhs'_any_rmemory p`lhs'_any_rcancr using output/table3/`lhs'_hlth.tex,  `NOMEAN_estout' keep(e0 a1) 

}

/* Main event table helper panels */
foreach lhs in any_helpr {
    /* Table 2 helper panel */
    estout p`lhs'_wneg2 p`lhs'_any_rlost_job p`lhs'_male_rwidowed p`lhs'_fem_rwidowed p`lhs'_any_rhosp p`lhs'_any_disab p`lhs'_any_health3to5  using output/table2/`lhs'_post.tex, `NOMEAN2_estout' keep(e0 a1) 
    filefilter output/table2/`lhs'_post.tex output/table2/`lhs'_post2.tex, from("Observations") to ("\BShline Observations") replace

    /* Table 4 helper panel */
    estout w1`lhs'_wneg2 w1`lhs'_any_rlost_job w1`lhs'_male_rwidowed w1`lhs'_fem_rwidowed w1`lhs'_any_rhosp w1`lhs'_any_disab w1`lhs'_any_health3to5 using output/table4/`lhs'_post_lw.tex, `NOMEAN2_estout' keep(e0 a1) 
    filefilter output/table4/`lhs'_post_lw.tex output/table4/`lhs'_post2_lw.tex, from("Observations") to ("\BShline Observations") replace

    /* Table 5 helper panel */
    estout w2`lhs'_wneg2 w2`lhs'_any_rlost_job w2`lhs'_male_rwidowed w2`lhs'_fem_rwidowed w2`lhs'_any_rhosp w2`lhs'_any_disab w2`lhs'_any_health3to5 using output/table5/`lhs'_post_hw.tex, `NOMEAN2_estout' keep(e0 a1) 
    filefilter output/table5/`lhs'_post_hw.tex output/table5/`lhs'_post2_hw.tex, from("Observations") to ("\BShline Observations") replace

    /* Table 3 helper panel */
    estout p`lhs'_any_rcardiac p`lhs'_any_rstrok  p`lhs'_any_rmemory p`lhs'_any_rcancr using output/table3/`lhs'_hlth.tex, `NOMEAN2_estout' keep(e0 a1) 
    filefilter output/table3/`lhs'_hlth.tex output/table3/`lhs'_hlth2.tex, from("Observations") to ("\BShline Observations") replace
}

//Other Outcomes//
foreach lhs in amt_pk amt_kp {
    estout p`lhs'_wneg2 p`lhs'_any_rlost_job  p`lhs'_male_rwidowed p`lhs'_fem_rwidowed p`lhs'_any_rhosp p`lhs'_any_disab p`lhs'_any_health3to5 using output/misc_tables/`lhs'_post.tex, `NOMEAN_estout' keep(e0 a1) 
}

foreach lhs in help_hrs {
    estout p`lhs'_wneg2 p`lhs'_any_rlost_job p`lhs'_male_rwidowed p`lhs'_fem_rwidowed p`lhs'_any_rhosp p`lhs'_any_disab p`lhs'_any_health3to5  using output/misc_tables/`lhs'_post.tex, `NOMEAN2_estout' keep(e0 a1) 
    filefilter output/misc_tables/`lhs'_post.tex output/misc_tables/`lhs'_post2.tex, from("Observations") to ("\BShline Observations") replace
}


/* Table 6 -- mechanisms */
foreach lhs in wlthpc incpc oop rbeq100 rliv75  {
    estout p`lhs'_wneg2 p`lhs'_any_rlost_job  p`lhs'_male_rwidowed p`lhs'_fem_rwidowed p`lhs'_any_rhosp p`lhs'_any_disab p`lhs'_any_health3to5 using output/table6/`lhs'_post.tex, `Mech_estout' keep(e0 a1) 
}

loc Mech_estout2 "stats( Observations Households, fmt(0 0)) cells(b(fmt(2) star) se(par fmt(2))) mlabels(none) la collabels(,none) eqlabels(none) varwidth(16) modelwidth(12) style(tex) starl(* 0.05 ** .01) rep"
foreach lhs in any_lv10 {
    estout p`lhs'_wneg2 p`lhs'_any_rlost_job  p`lhs'_male_rwidowed p`lhs'_fem_rwidowed p`lhs'_any_rhosp p`lhs'_any_disab p`lhs'_any_health3to5 using output/table6/`lhs'_post.tex, `Mech_estout2' keep(e0 a1) 
    filefilter output/table6/`lhs'_post.tex output/table6/`lhs'_post2.tex, from("Observations") to ("\BShline Observations") replace
}

clear



//***********************************//
//***********************************//
//***********Event Study Graphs******//
//***********************************//
//***********************************//
/* These are for figures 2-4 and 7 */
foreach event in wneg2 any_rlost_job fem_rwidowed male_rwidowed any_disab any_rhosp any_health3to5  {

use "output/event_study_regsave/`event'_at_pk.dta", clear
keep var coef ci_lower ci_upper group

gen t = -3 if var=="b3m"
replace t = -2 if var=="b2"
replace t = 0 if var=="e0"
replace t = 1 if var=="a1"
replace t = 2 if var=="a2"
replace t = 3 if var=="a3"

drop var

sort t
reshape wide coef ci_lower ci_upper, i(t) j(group) string

set obs 7
replace t = -1 if t==.
sort t

foreach n of varlist coef* ci* {
replace `n' = 0 if t==-1
}

     label var t "Waves Since Event Recorded"

twoway line coeffull t, lcolor(black) title("Parent to Child Transfer", size(vlarge)) xlabel(-3(1)3, labsize(vlarge)) ylabel(-.05(.05).05, labsize(vlarge)) || ///
	line ci_lowerfull t, graphregion(color(white)) lcolor(black) lpattern(dot) legend(off) xtitle(, size(vlarge)) || ///
	line ci_upperfull t, lcolor(black) lpattern(dot) yline(0, lcolor(gs12)) xline(-0.5, lcolor(gs12) lpattern(dash))
	
graph export "output/figures234/`event'_at_pk.pdf", replace



use "output/event_study_regsave/`event'_at_kp.dta", clear
keep var coef ci_lower ci_upper group


gen t = -3 if var=="b3m"
replace t = -2 if var=="b2"
replace t = 0 if var=="e0"
replace t = 1 if var=="a1"
replace t = 2 if var=="a2"
replace t = 3 if var=="a3"

drop var

sort t
reshape wide coef ci_lower ci_upper, i(t) j(group) string

set obs 7
replace t = -1 if t==.
sort t

foreach n of varlist coef* ci* {
replace `n' = 0 if t==-1
}


     label var t "Waves Since Event Recorded"

twoway line coeffull t, lcolor(black) title("Child to Parent Transfer", size(vlarge)) xlabel(-3(1)3, labsize(vlarge)) ylabel(-0.05(.05)0.05, labsize(vlarge)) || ///
	line ci_lowerfull t, graphregion(color(white)) lcolor(black) lpattern(dot) legend(off) xtitle(, size(vlarge))  || ///
	line ci_upperfull t, lcolor(black) lpattern(dot) yline(0, lcolor(gs12)) xline(-0.5, lcolor(gs12) lpattern(dash))
graph export "output/figures234/`event'_at_kp.pdf", replace


/* Any helper graphs */
use "output/event_study_regsave/`event'_any_helpr.dta", clear
keep var coef ci_lower ci_upper group


gen t = -3 if var=="b3m"
replace t = -2 if var=="b2"
replace t = 0 if var=="e0"
replace t = 1 if var=="a1"
replace t = 2 if var=="a2"
replace t = 3 if var=="a3"

drop var

sort t
reshape wide coef ci_lower ci_upper, i(t) j(group) string

set obs 7
replace t = -1 if t==.
sort t

foreach n of varlist coef* ci* {
replace `n' = 0 if t==-1
}


     label var t "Waves Since Event Recorded"

twoway line coeffull t, lcolor(black) title("Child Helping", size(vlarge)) xlabel(-3(1)3, labsize(vlarge)) ylabel(-0.05(.05).1, labsize(vlarge)) || ///
	line ci_lowerfull t, graphregion(color(white)) lcolor(black) lpattern(dot) legend(off) xtitle(, size(vlarge)) || ///
	line ci_upperfull t, lcolor(black) lpattern(dot) yline(0, lcolor(gs12)) xline(-0.5, lcolor(gs12) lpattern(dash))
graph export "output/figures234/`event'_any_helpr.pdf", replace

}


//Widow graphs with different scale
/* Figure 3 */
foreach event in fem_rwidowed male_rwidowed {
use "output/event_study_regsave/`event'_at_pk.dta", clear
keep var coef ci_lower ci_upper group


gen t = -3 if var=="b3m"
replace t = -2 if var=="b2"
replace t = 0 if var=="e0"
replace t = 1 if var=="a1"
replace t = 2 if var=="a2"
replace t = 3 if var=="a3"

drop var

sort t
reshape wide coef ci_lower ci_upper, i(t) j(group) string

set obs 7
replace t = -1 if t==.
sort t

foreach n of varlist coef* ci* {
replace `n' = 0 if t==-1
}

     label var t "Waves Since Event Recorded"

twoway line coeffull t, lcolor(black) title("Parent to Child Transfer", size(vlarge)) xlabel(-3(1)3, labsize(vlarge)) ylabel(-.05(.05).2, labsize(vlarge)) || ///
	line ci_lowerfull t, graphregion(color(white)) lcolor(black) lpattern(dot) legend(off) xtitle(, size(vlarge)) || ///
	line ci_upperfull t, lcolor(black) lpattern(dot) yline(0, lcolor(gs12)) xline(-0.5, lcolor(gs12) lpattern(dash))
graph export "output/figures234/`event'_at_pk.pdf", replace


}

foreach event in any_health3to5  {

use "output/event_study_regsave/`event'_at_pk.dta", clear
keep var coef ci_lower ci_upper group

gen t = -3 if var=="b3m"
replace t = -2 if var=="b2"
replace t = 0 if var=="e0"
replace t = 1 if var=="a1"
replace t = 2 if var=="a2"
replace t = 3 if var=="a3"

drop var

sort t
reshape wide coef ci_lower ci_upper, i(t) j(group) string

set obs 7
replace t = -1 if t==.
sort t

foreach n of varlist coef* ci* {
replace `n' = 0 if t==-1
}

     label var t "Waves Since Event Recorded"

twoway line coeffull t, lcolor(black) title("Parent to Child Transfer", size(vlarge)) xlabel(-3(1)3, labsize(vlarge)) ylabel(-.05(.05).05, labsize(vlarge)) || ///
	line ci_lowerfull t, graphregion(color(white)) lcolor(black) lpattern(dot) legend(off) xtitle(, size(vlarge)) || ///
	line ci_upperfull t, lcolor(black) lpattern(dot) yline(0, lcolor(gs12)) xline(-0.5, lcolor(gs12) lpattern(dash))
	
graph export "output/figures234/`event'_at_pk.pdf", replace
}




/* Each section creates panels for figure 5 */



/* This is panel A  */
/* It uses kid-level data, so it's in another file */
do "code/figure5_bygender.do"




//***********************************//
//***********************************//
//***********************************//
/*Medicare elig Graphs*/
//***********************************//
//***********************************//
//***********************************//
/* Figure 5: panel B */
/* Also figure B4 Panel C */
foreach lhs in at_pk at_kp any_helpr {
foreach event in  any_rcancr any_rstrok any_rcardiac any_rmemory any_disab any_rhosp any_health3to5 { //   {
        if "`event'" == "any_rwidowed"{
            loc title "Parental Death"
        }
        else if "`event'" == "any_rhosp" {
            loc title "Any Hospitalization"
        } 
        else if "`event'" == "any_health3to5" {
            loc title "Poor Health"
        }
        else if "`event'" == "any_disab" {
            loc title "Disability Onset"
        } 
        else if "`event'" == "any_rcancr" {
            loc title "Cancer"
        }
        else if "`event'" == "any_rstrok" {
            loc title "Stroke"
        }
        else if "`event'" == "any_rcardiac" {
            loc title "Cardiac"
        }
        else if "`event'" == "any_rmemory" {
            loc title "Memory"
        }


clear
use "output/event_study_regsave/`event'_`lhs'_byage.dta"

keep var coef ci_lower ci_upper group

gen t = -3 if var=="b3m"
replace t = -2 if var=="b2"
replace t = 0 if var=="e0"
replace t = 1 if var=="a1"
replace t = 2 if var=="a2"
replace t = 3 if var=="a3"


drop var

sort t
reshape wide coef ci_lower ci_upper, i(t) j(group) string

set obs 7
replace t = -1 if t==.
sort t

foreach n of varlist coef* ci* {
replace `n' = 0 if t==-1
}

label var t "Waves Since Event Recorded"

twoway line coef55_64 t, lcolor(black) lpattern(dash) graphregion(color(white)) || line coef65_74 t, lcolor(black)   title("`title'", size(vlarge)) xlabel(-3(1)3, labsize(vlarge)) ylabel(-.05(.05).1, labsize(vlarge)) yline(0, lcolor(gs12)) xline(-0.5, lcolor(gs12) lpattern(dash)) legend(label(1 "Ages 55 to 64") label(2 "Ages 65-74") )
graph export "output/byage/`event'_`lhs'_byage.pdf", replace


}
}


//***********************************//
//***********************************//
//***********************************//
/*High vs. Low Wealth Graphs*/
//***********************************//
//***********************************//
//***********************************//
/* Figure 5 Panel C */
/* Figure B4 panel B */

foreach event in any_rcancr any_rstrok any_rcardiac any_rmemory  any_disab any_rhosp any_health3to5 {
        if "`event'" == "any_rwidowed"{
            loc title "Parental Death"
        }
        else if "`event'" == "any_rhosp" {
            loc title "Any Hospitalization"
        } 
        else if "`event'" == "any_health3to5" {
            loc title "Poor Health"
        }
        else if "`event'" == "any_disab" {
            loc title "Disability Onset"
        } 
        else if "`event'" == "any_rcancr" {
            loc title "Cancer"
        }
        else if "`event'" == "any_rstrok" {
            loc title "Stroke"
        }
        else if "`event'" == "any_rcardiac" {
            loc title "Cardiac"
        }
        else if "`event'" == "any_rmemory" {
            loc title "Memory"
        }

	
clear
use "output/event_study_regsave/`event'_any_helpr_lw.dta"
append using "output/event_study_regsave/`event'_any_helpr_hw.dta"

keep var coef ci_lower ci_upper group

gen t = -3 if var=="b3m"
replace t = -2 if var=="b2"
replace t = 0 if var=="e0"
replace t = 1 if var=="a1"
replace t = 2 if var=="a2"
replace t = 3 if var=="a3"


drop var

sort t
reshape wide coef ci_lower ci_upper, i(t) j(group) string

set obs 7
replace t = -1 if t==.
sort t

foreach n of varlist coef* ci* {
replace `n' = 0 if t==-1
}

     label var t "Waves Since Event Recorded"

twoway line coeflw t, lcolor(black) graphregion(color(white)) || line coefhw t, lcolor(black) lpattern(dash)  title("`title'", size(vlarge)) xlabel(-3(1)3, labsize(vlarge)) ylabel(-.05(.05).1, labsize(vlarge)) yline(0, lcolor(gs12)) xline(-0.5, lcolor(gs12) lpattern(dash)) legend(label(1 "Low Wealth") label(2 "High Wealth") )
graph export "output/byhhwealth/`event'_any_helpr_byw.pdf", replace


}

/* Figure 5 -- Panel D */
/* Also figure B4 Panel D */
//////////////////////////////////////////
/* Heterogeneity by Family Structure  */
/////////////////////////////////////////

use data/constructed_data/analysisdata.dta, clear 
loc regsave_path output/event_study_regsave
loc plot_path output/byhhstructure
loc lhs_vars  any_helpr 
loc event_vars  any_health3to5 any_rcancr any_rstrok any_rcardiac any_rmemory wneg2 any_rlost_job any_rhosp any_disab

/* prep reg data for graphs */
foreach event in `event_vars' {
	foreach lhs in `lhs_vars' { 
        use "`regsave_path'/`event'_`lhs'_byhhstructure.dta", clear
        
        cap drop t 
        gen t = -3 if var=="b3m"
        replace t = -2 if var=="b2"
        replace t = 0 if var=="e0"
        replace t = 1 if var=="a1"
        replace t = 2 if var=="a2"
        replace t = 3 if var=="a3"
        drop if mi(t)

        replace group = "`samp'" if t == -1
        cap drop event
        gen event = "`event'"
        save "`regsave_path'/`event'_`lhs'_byhhstructure.dta", replace
    }
}

loc regsave_path output/event_study_regsave
loc plot_path output/byhhstructure
loc lhs_vars  any_helpr 
loc event_vars  any_health3to5 any_rcancr any_rstrok any_rcardiac any_rmemory wneg2 any_rlost_job any_rhosp any_disab

/* graphs */
foreach l in `lhs_vars' {
    foreach e in `event_vars' {
         // load regression results        
        use "`regsave_path'/`e'_`l'_byhhstructure.dta", clear

        // rename for graphing and add -1 -- did this in batch above I thnik
        keep t coef ci_lower ci_upper group

        sort t
        reshape wide coef ci_lower ci_upper, i(t) j(group) string
        
        set obs 7 
        replace t = -1 if t==.
        sort t

        foreach n of varlist coef* ci_* {
            replace `n' = 0 if t==-1
        }

        label var t "Waves Since Event Recorded"
        if "`e'" == "any_rhosp" {
            loc title "Any Hospitalization"
        } 
        else if "`e'" == "any_health3to5" {
            loc title "Poor Health"
        }
        else if "`e'" == "any_disab" {
            loc title "Disability Onset"
        } 
        else if "`e'" == "any_rcancr" {
            loc title "Cancer"
        }
        else if "`e'" == "any_rstrok" {
            loc title "Stroke"
        }
        else if "`e'" == "any_rcardiac" {
            loc title "Cardiac"
        }
        else if "`e'" == "any_rmemory" {
            loc title "Memory"
        }
        else {
            loc title "Effect of `e' on `lhs'"
        }

        // manually construct plot using each coef column
        twoway line coefs t, lcolor(black) graphregion(color(white)) || ///
        line coefcpl t, lcolor(black) lpattern(dash) title("`title'", size(vlarge)) xlabel(-3(1)3, labsize(vlarge)) ylabel(-.05(.05).05, labsize(vlarge)) yline(0, lcolor(gs12)) xline(-0.5, lcolor(gs12) lpattern(dash)) legend(order(1 "Single" 2 "Couple"))

        // save
        graph export "`plot_path'/`e'_`l'_byhhstructure.pdf", replace

    }
}



/* Figure 6 */
clear
foreach event in any_disab any_rhosp any_health3to5 any_rcardiac any_rmemory any_rcancr  {
    use "output/event_study_regsave/`event'_fkh_apk.dta", clear
    keep var coef ci_lower ci_upper group

    gen t = -3 if var=="b3m"
    replace t = -2 if var=="b2"
    replace t = 0 if var=="e0"
    replace t = 1 if var=="a1"
    replace t = 2 if var=="a2"
    replace t = 3 if var=="a3"

    label var t "Waves Since Event Recorded"
    drop var

    sort t
    reshape wide coef ci_lower ci_upper, i(t) j(group) string

    set obs 7
    replace t = -1 if t==.
    sort t

    foreach n of varlist coef* ci* {
        replace `n' = 0 if t==-1
        }


    label var t "Waves Since Event Recorded"

            // manually construct plot using each coef column
    qui twoway line coef t, lcolor(black) graphregion(color(white)) xlabel(-3(1)3, labsize(vlarge)) ylabel(-.05(.05).05, labsize(vlarge)) yline(0, lcolor(gs12)) xline(-0.5, lcolor(gs12) lpattern(dash)) legend(off) || ///
            line ci_lower t, lcolor(black) lpattern(dot) || ///
            line ci_upper t, lcolor(black) lpattern(dot) 
    graph export "output/figure6/`event'_frac_kh_amtpk.pdf", replace

}

//***********************************//
//***********************************//
//***********************************//
/*Home vs. Market Care Graphs*/
//***********************************//
//***********************************//
//***********************************//
/* This is figure 7 */
use "output/event_study_regsave/wneg2_any_helpr.dta", clear
replace group = "wneg2" if group=="full"

foreach event in  any_rlost_job fem_rwidowed male_rwidowed any_disab any_rhosp any_health3to5  {
    append using "output/event_study_regsave/`event'_any_helpr.dta"
    replace group = "`event'" if group=="full"
}


keep var coef ci_lower ci_upper group

gen t = -3 if var=="b3m"
replace t = -2 if var=="b2"
replace t = 0 if var=="e0"
replace t = 1 if var=="a1"
replace t = 2 if var=="a2"
replace t = 3 if var=="a3"


drop var

sort t
reshape wide coef ci_lower ci_upper, i(t) j(group) string

set obs 7
replace t = -1 if t==.
sort t

foreach n of varlist coef* ci* {
replace `n' = 0 if t==-1
}

label var t "Waves Since Event Recorded"

twoway line coeffem_rwidowed t, lcolor(black) graphregion(color(white)) || line coefany_rhosp t, lcolor(black) lpattern(dot)  title("Any Child Helping", size(vlarge)) xlabel(-3(1)3, labsize(vlarge)) ylabel(-.05(.05).15, labsize(vlarge)) yline(0, lcolor(gs12)) xline(-0.5, lcolor(gs12) lpattern(dash)) || line coefany_disab t, lcolor(black) lpattern(dash) legend(label(1 "Female Widowed") label(2 "Any Hospitalization") label(3 "Disability Onset") label(4 "Poor Health")) || line coefany_health3to5 t, lcolor(gray) 

graph export "output/figure7/helpr_compare.pdf", replace

use "output/event_study_regsave/wneg2_any_hcr.dta", clear
replace group = "wneg2" if group=="full"


foreach event in  any_rlost_job fem_rwidowed male_rwidowed any_disab any_rhosp any_health3to5  {
append using "output/event_study_regsave/`event'_any_hcr.dta"
replace group = "`event'" if group=="full"
}


keep var coef ci_lower ci_upper group

gen t = -3 if var=="b3m"
replace t = -2 if var=="b2"
replace t = 0 if var=="e0"
replace t = 1 if var=="a1"
replace t = 2 if var=="a2"
replace t = 3 if var=="a3"


drop var

sort t
reshape wide coef ci_lower ci_upper, i(t) j(group) string

set obs 7
replace t = -1 if t==.
sort t

foreach n of varlist coef* ci* {
    replace `n' = 0 if t==-1
}

label var t "Waves Since Event Recorded"

twoway line coeffem_rwidowed t, lcolor(black) || line coefany_rhosp t, lcolor(black) lpattern(dot) graphregion(color(white))  title("Any Market/Formal Care", size(vlarge)) xlabel(-3(1)3, labsize(vlarge)) ylabel(-.05(.05).15, labsize(vlarge)) yline(0, lcolor(gs12)) xline(-0.5, lcolor(gs12) lpattern(dash)) || line coefany_disab t, lcolor(black) lpattern(dash) legend(label(1 "Female Widowed") label(2 "Any Hospitalization") label(3 "Disability Onset") label(4 "Poor Health")) || line coefany_health3to5 t, lcolor(gray) 

graph export "output/figure7/mkthcr_compare.pdf", replace


/* Create panel B*/
use "output/event_study_regsave/any_rcardiac_any_helpr.dta", clear
replace group = "any_rcardiac" if group=="full"


foreach event in any_rstrok any_rmemory any_rcancr {
    append using "output/event_study_regsave/`event'_any_helpr.dta"
    replace group = "`event'" if group=="full"
}


keep var coef ci_lower ci_upper group

gen t = -3 if var=="b3m"
replace t = -2 if var=="b2"
replace t = 0 if var=="e0"
replace t = 1 if var=="a1"
replace t = 2 if var=="a2"
replace t = 3 if var=="a3"


drop var

sort t
reshape wide coef ci_lower ci_upper, i(t) j(group) string

set obs 7
replace t = -1 if t==.
sort t

foreach n of varlist coef* ci* {
replace `n' = 0 if t==-1
}

     label var t "Waves Since Event Recorded"

twoway line coefany_rcardiac t, lcolor(black) graphregion(color(white)) || line coefany_rstrok t, lcolor(black) lpattern(dot)  title("Any Child Helping", size(vlarge)) xlabel(-3(1)3, labsize(vlarge)) ylabel(-.05(.05).15, labsize(vlarge)) yline(0, lcolor(gs12)) xline(-0.5, lcolor(gs12) lpattern(dash)) || line coefany_rmemory t, lcolor(black) lpattern(dash) legend(label(1 "Cardiac") label(2 "Stroke") label(3 "Memory") label(4 "Cancer")) || line coefany_rcancr t, lcolor(gray) 

graph export "output/figure7/helpr_compare_specific.pdf", replace





use "output/event_study_regsave/any_rcardiac_any_hcr.dta", clear
replace group = "any_rcardiac" if group=="full"


foreach event in any_rstrok any_rmemory any_rcancr {
append using "output/event_study_regsave/`event'_any_hcr.dta"
replace group = "`event'" if group=="full"
}


keep var coef ci_lower ci_upper group

gen t = -3 if var=="b3m"
replace t = -2 if var=="b2"
replace t = 0 if var=="e0"
replace t = 1 if var=="a1"
replace t = 2 if var=="a2"
replace t = 3 if var=="a3"


drop var

sort t
reshape wide coef ci_lower ci_upper, i(t) j(group) string

set obs 7
replace t = -1 if t==.
sort t

foreach n of varlist coef* ci* {
replace `n' = 0 if t==-1
}

     label var t "Waves Since Event Recorded"

twoway line coefany_rcardiac t, lcolor(black) graphregion(color(white)) || line coefany_rstrok t, lcolor(black) lpattern(dot)  title("Any Market/Formal Care", size(vlarge)) xlabel(-3(1)3, labsize(vlarge)) ylabel(-.05(.05).15, labsize(vlarge)) yline(0, lcolor(gs12)) xline(-0.5, lcolor(gs12) lpattern(dash)) || line coefany_rmemory t, lcolor(black) lpattern(dash) legend(label(1 "Cardiac") label(2 "Stroke") label(3 "Memory") label(4 "Cancer")) || line coefany_rcancr t, lcolor(gray) 

graph export "output/figure7/mkthcr_compare_specific.pdf", replace




//***********************************//
//***********************************//
//***********Alternate Specifications ************//
//***********************************//
//***********************************//

//***********************************//
//***********************************//
//***********Borusyak Specification ************//
//***********************************//
//***********************************//

/* This is done in borusyak.do */
do code/borusyak.do 

//***********************************//
//***********************************//
//***********Event Study - Equation 2 Semi-Parametric ************//
//***********************************//
//***********************************//
/* this is table c3 -- controlling for pre-trends */
estimates clear

use data/constructed_data/analysisdata.dta, clear

foreach event in wneg2 any_rlost_job any_rhosp any_disab any_health3to5 {
di "`event'"
preserve

//Setup
gen temp = 1 if `event'==1 & l.`event'==0 & l2.`event'==0 & any_rwidowed==0
bys hhidpn: egen firstevent = min(wave*temp)
drop temp
gen eventtime = wave - firstevent 
gen eventever = firstevent~=.
keep if eventever==1  

//Event indicators
gen b3m = eventtime<=-3
gen b2 = eventtime==-2
gen b1 = eventtime==-1
gen e0 = eventtime==0
gen a1 = eventtime==1
gen a2 = eventtime==2
gen a3m = eventtime>=3
forvalues l = 3/9 {
gen a`l' = eventtime==`l'
}

//Regressions 
foreach lhs of varlist at_pk at_kp any_helpr  {
di "`lhs'"
qui xtreg `lhs' eventtime e0 a1 a2 a3 a4 a5 a6 a7 a8 a9 oldest_age oldest_age2 i.wave [pweight = weight], fe cluster(hhidpn)
eststo p`lhs'_`event'
}
restore
}

use data/constructed_data/analysisdata.dta, clear

loc events "male_rwidowed fem_rwidowed"

foreach event in `events' {
di "`event'"
preserve

//Setup
gen temp = 1 if `event'==1  & l.`event'==0 & l2.`event'==0
bys hhidpn: egen firstevent = min(wave*temp)
drop temp
gen eventtime = wave - firstevent 
gen eventever = firstevent~=.
keep if eventever==1  

//Event indicators
gen b3m = eventtime<=-3
gen b2 = eventtime==-2
gen b1 = eventtime==-1
gen e0 = eventtime==0
gen a1 = eventtime==1
gen a2 = eventtime==2
gen a3m = eventtime>=3
forvalues l = 3/9 {
gen a`l' = eventtime==`l'
}
//Regressions 
foreach lhs of varlist at_pk at_kp any_helpr  {
di "`lhs'"
qui xtreg `lhs' eventtime e0 a1 a2 a3 a4 a5 a6 a7 a8 a9 oldest_age oldest_age2 i.wave [pweight = weight], fe cluster(hhidpn)
eststo p`lhs'_`event'
}
restore
}

foreach n in e0 a1 a2 {
gen `n' = .
}

     label var e0 "Event Wave"
     label var a1 "One Wave After"

foreach lhs in at_pk at_kp any_helpr  {
estout p`lhs'_wneg2 p`lhs'_any_rlost_job  p`lhs'_male_rwidowed p`lhs'_fem_rwidowed p`lhs'_any_rhosp p`lhs'_any_disab p`lhs'_any_health3to5  ///
	using output/tablec3/`lhs'_post_eq2.tex, `NOMEAN_estout' keep(e0 a1) 
}
clear



//***********************************//
//***********************************//
//***********Event Study - Unweighted ************//
//***********************************//
//***********************************//
/* TABLE c4 */
estimates clear

use data/constructed_data/analysisdata.dta, clear

foreach event in wneg2 any_rlost_job any_rhosp any_disab any_health3to5 {
di "`event'"
preserve

//Setup
gen temp = 1 if `event'==1 & l.`event'==0 & l2.`event'==0 & any_rwidowed==0
bys hhidpn: egen firstevent = min(wave*temp)
drop temp
gen eventtime = wave - firstevent 
gen eventever = firstevent~=.
keep if eventever==1  

//Event indicators
gen b3m = eventtime<=-3
gen b2 = eventtime==-2
gen b1 = eventtime==-1
gen e0 = eventtime==0
gen a1 = eventtime==1
gen a2 = eventtime==2
gen a3m = eventtime>=3
forvalues l = 3/9 {
gen a`l' = eventtime==`l'
}


//Regressions 
foreach lhs of varlist at_pk at_kp any_helpr  {
di "`lhs'"
qui xtreg `lhs' b3m b2 e0 a1 a2 a3 a4 a5 a6 a7 a8 a9 oldest_age oldest_age2 i.wave, fe cluster(hhidpn)
qui estadd scalar Observations = e(N)
qui estadd scalar Households = e(N_g)
su `lhs' [weight = weight] if e(sample)==1 & eventtime<0
qui estadd scalar Mean = r(mean)
eststo p`lhs'_`event'
}

restore
}



use data/constructed_data/analysisdata.dta, clear

loc events "male_rwidowed fem_rwidowed"

foreach event in `events' {
di "`event'"
preserve

//Setup
gen temp = 1 if `event'==1  & l.`event'==0 & l2.`event'==0
bys hhidpn: egen firstevent = min(wave*temp)
drop temp
gen eventtime = wave - firstevent 
gen eventever = firstevent~=.
keep if eventever==1  

//Event indicators
gen b3m = eventtime<=-3
gen b2 = eventtime==-2
gen b1 = eventtime==-1
gen e0 = eventtime==0
gen a1 = eventtime==1
gen a2 = eventtime==2
gen a3m = eventtime>=3
forvalues l = 3/9 {
gen a`l' = eventtime==`l'
}



//Regressions 
foreach lhs of varlist at_pk at_kp any_helpr  {
di "`lhs'"
qui xtreg `lhs' b3m b2 e0 a1 a2 a3 a4 a5 a6 a7 a8 a9 oldest_age oldest_age2 i.wave, fe cluster(hhidpn)
qui estadd scalar Observations = e(N)
qui estadd scalar Households = e(N_g)
su `lhs' [weight = weight] if e(sample)==1 & eventtime<0
qui estadd scalar Mean = r(mean)
eststo p`lhs'_`event'
}

restore
}


//ES Tables
foreach n in e0 a1 a2 {
gen `n' = .
}

     label var e0 "Event Wave"
     label var a1 "One Wave After"

foreach lhs in at_pk at_kp any_helpr  {
estout p`lhs'_wneg2 p`lhs'_any_rlost_job  p`lhs'_male_rwidowed p`lhs'_fem_rwidowed p`lhs'_any_rhosp p`lhs'_any_disab p`lhs'_any_health3to5  ///
	using output/tablec4/`lhs'_post_unw.tex, `NOMEAN_estout' keep(e0 a1) 
}

clear






//***********************************//
//***********************************//
//***********Event Study - With Control Group ************//
//***********************************//
//***********************************//
/* This is table C5 */
estimates clear
use data/constructed_data/analysisdata.dta, clear

foreach event in wneg2 any_rlost_job any_rhosp any_disab any_health3to5 {
di "`event'"
preserve

//Setup
gen temp = 1 if `event'==1 & l.`event'==0 & l2.`event'==0 & any_rwidowed==0
bys hhidpn: egen firstevent = min(wave*temp)
drop temp
gen eventtime = wave - firstevent 
gen eventever = firstevent~=.
*keep if eventever==1  

//Event indicators
gen b3m = eventtime<=-3
gen b2 = eventtime==-2
gen b1 = eventtime==-1
gen e0 = eventtime==0
gen a1 = eventtime==1
gen a2 = eventtime==2
gen a3m = eventtime>=3
forvalues l = 3/9 {
gen a`l' = eventtime==`l'
}


//Regressions 
foreach lhs of varlist at_pk at_kp any_helpr  {
di "`lhs'"
qui xtreg `lhs' b3m b2 e0 a1 a2 a3 a4 a5 a6 a7 a8 a9 oldest_age oldest_age2 i.wave eventever [pweight = weight], fe cluster(hhidpn)
qui estadd scalar Observations = e(N)
qui estadd scalar Households = e(N_g)
su `lhs' [weight = weight] if e(sample)==1 & eventtime<0
qui estadd scalar Mean = r(mean)
eststo p`lhs'_`event'
}

restore
}



use data/constructed_data/analysisdata.dta, clear

loc events "male_rwidowed fem_rwidowed"

foreach event in `events' {
    di "`event'"
    preserve

    //Setup
    gen temp = 1 if `event'==1  & l.`event'==0 & l2.`event'==0
    bys hhidpn: egen firstevent = min(wave*temp)
    drop temp
    gen eventtime = wave - firstevent 
    gen eventever = firstevent~=.
    *keep if eventever==1  

    //Event indicators
    gen b3m = eventtime<=-3
    gen b2 = eventtime==-2
    gen b1 = eventtime==-1
    gen e0 = eventtime==0
    gen a1 = eventtime==1
    gen a2 = eventtime==2
    gen a3m = eventtime>=3
    forvalues l = 3/9 {
        gen a`l' = eventtime==`l'
    }



//Regressions 
    foreach lhs of varlist at_pk at_kp any_helpr  {
        di "`lhs'"
        qui xtreg `lhs' b3m b2 e0 a1 a2 a3 a4 a5 a6 a7 a8 a9 oldest_age oldest_age2 i.wave eventever [pweight = weight], fe cluster(hhidpn)
        qui estadd scalar Observations = e(N)
        qui estadd scalar Households = e(N_g)
        su `lhs' [weight = weight] if e(sample)==1 & eventtime<0
        qui estadd scalar Mean = r(mean)
        eststo p`lhs'_`event'
    }

    restore
}


//ES Tables
foreach n in e0 a1 a2 {
    gen `n' = .
}

     label var e0 "Event Wave"
     label var a1 "One Wave After"

foreach lhs in at_pk at_kp  any_helpr {
estout p`lhs'_wneg2 p`lhs'_any_rlost_job  p`lhs'_male_rwidowed p`lhs'_fem_rwidowed p`lhs'_any_rhosp p`lhs'_any_disab p`lhs'_any_health3to5  ///
	using output/tablec5/`lhs'_post_cntrl.tex, `NOMEAN_estout' keep(e0 a1) 
}
clear



















/*JL and Wealth Alternates*/
/* Table C2 */
//***********************************//
//***********************************//
//***********Job Exits ************//
//***********************************//
//***********************************//
estimates clear

use data/constructed_data/analysisdata.dta, clear

rename female_rlost_job fem_jl
rename male_rlost_job male_jl
rename any_jl_badhealth health_jl
rename any_rlost_job invol_jl

foreach event in male_jl fem_jl invol_jl health_jl {
    di "`event'"
    preserve

    //Setup
    gen temp = 1 if `event'==1 & l.`event'==0 & l2.`event'==0 & any_rwidowed==0
    bys hhidpn: egen firstevent = min(wave*temp)
    drop temp
    gen eventtime = wave - firstevent 
    gen eventever = firstevent~=.
    keep if eventever==1  

    //Event indicators
    gen b3m = eventtime<=-3
    gen b2 = eventtime==-2
    gen b1 = eventtime==-1
    gen e0 = eventtime==0
    gen a1 = eventtime==1
    gen a2 = eventtime==2
    gen a3m = eventtime>=3
    forvalues l = 3/9 {
        gen a`l' = eventtime==`l'
    }



    //Regressions 
    foreach lhs of varlist at_pk at_kp any_helpr {
        di "`lhs'"
        qui xtreg `lhs' b3m b2 e0 a1 a2 a3m oldest_age oldest_age2 i.wave [pweight = weight], fe cluster(hhidpn)
        qui estadd scalar Observations = e(N)
        qui estadd scalar Households = e(N_g)
        su `lhs' [w=weight] if e(sample)==1 & eventtime<0
        qui estadd scalar Mean = r(mean)
        eststo p`lhs'_`event'
    }

    restore
}


//ES Tables
foreach n in e0 a1 a2 {
    gen `n' = .
}

label var e0 "Event Wave"
label var a1 "One Wave After"

foreach lhs in at_pk at_kp {
    estout p`lhs'_male_jl p`lhs'_fem_jl  p`lhs'_invol_jl p`lhs'_health_jl using output/tablec2/`lhs'_post_jl.tex, `NOMEAN_estout' keep(e0 a1) 
}

foreach lhs in any_helpr {
    estout p`lhs'_male_jl p`lhs'_fem_jl  p`lhs'_invol_jl p`lhs'_health_jl using output/tablec2/`lhs'_post_jl.tex, `NOMEAN2_estout' keep(e0 a1) 
    filefilter output/tablec2/`lhs'_post_jl.tex output/tablec2/`lhs'_post2_jl.tex, from("Observations") to ("\BShline Observations") replace
}





//***********************************//
//***********************************//
//***********Wealth Shocks ************//
//***********************************//
//***********************************//
use data/constructed_data/analysisdata.dta, clear


rename wshock_nonhouse wshock_nh

foreach event in wshock_nh wshock_nhf {
    di "`event'"
    preserve

    //Setup
    gen temp = 1 if `event'==1 & l.`event'==0 & l2.`event'==0 & any_rwidowed==0
    bys hhidpn: egen firstevent = min(wave*temp)
    drop temp
    gen eventtime = wave - firstevent 
    gen eventever = firstevent~=.
    keep if eventever==1  

    //Event indicators
    gen b3m = eventtime<=-3
    gen b2 = eventtime==-2
    gen b1 = eventtime==-1
    gen e0 = eventtime==0
    gen a1 = eventtime==1
    gen a2 = eventtime==2
    gen a3m = eventtime>=3
    forvalues l = 3/9 {
        gen a`l' = eventtime==`l'
    }
    //Regressions 
    foreach lhs of varlist at_pk at_kp any_helpr {
        di "`lhs'"
        qui xtreg `lhs' b3m b2 e0 a1 a2 a3m oldest_age oldest_age2 i.wave [pweight = weight], fe cluster(hhidpn)
        qui estadd scalar Observations = e(N)
        qui estadd scalar Households = e(N_g)
        su `lhs' [w=weight] if e(sample)==1 & eventtime<0
        qui estadd scalar Mean = r(mean)
        eststo p`lhs'_`event'
    }

    restore
}

foreach event in wneg2 {

    di "`event'"
    preserve

    //Setup
    gen temp = 1 if `event'==1 & l.`event'==0 & l2.`event'==0 & any_rwidowed==0 & any_nrshmchange==0
    bys hhidpn: egen firstevent = min(wave*temp)
    drop temp
    gen eventtime = wave - firstevent 
    gen eventever = firstevent~=.
    keep if eventever==1  

    //Event indicators
    gen b3m = eventtime<=-3
    gen b2 = eventtime==-2
    gen b1 = eventtime==-1
    gen e0 = eventtime==0
    gen a1 = eventtime==1
    gen a2 = eventtime==2
    gen a3m = eventtime>=3
    forvalues l = 3/9 {
        gen a`l' = eventtime==`l'
    }

    //Regressions 
    foreach lhs of varlist at_pk at_kp any_helpr {
        di "`lhs'"
        qui xtreg `lhs' b3m b2 e0 a1 a2 a3m oldest_age oldest_age2 i.wave [pweight = weight], fe cluster(hhidpn)
        qui estadd scalar Observations = e(N)
        qui estadd scalar Households = e(N_g)
        su `lhs' [w=weight] if e(sample)==1 & eventtime<0
        qui estadd scalar Mean = r(mean)
        eststo p`lhs'_`event'_nonrs
    }

    restore
}

foreach event in wneg2 {
    use data/constructed_data/analysisdata.dta if noimp_hou==1, clear

    di "`event'" 
    preserve

    //Setup
    gen temp = 1 if `event'==1 & l.`event'==0 & l2.`event'==0 & any_rwidowed==0
    bys hhidpn: egen firstevent = min(wave*temp)
    drop temp
    gen eventtime = wave - firstevent 
    gen eventever = firstevent~=.
    keep if eventever==1  

    //Event indicators
    gen b3m = eventtime<=-3
    gen b2 = eventtime==-2
    gen b1 = eventtime==-1
    gen e0 = eventtime==0
    gen a1 = eventtime==1
    gen a2 = eventtime==2
    gen a3m = eventtime>=3
    forvalues l = 3/9 {
        gen a`l' = eventtime==`l'
    }

    //Regressions 
    foreach lhs of varlist at_pk at_kp any_helpr {
        di "`lhs'"
        qui xtreg `lhs' b3m b2 e0 a1 a2 a3m oldest_age oldest_age2 i.wave [pweight = weight], fe cluster(hhidpn)

        qui estadd scalar Observations = e(N)
        qui estadd scalar Households = e(N_g)
        su `lhs' [w=weight] if e(sample)==1 & eventtime<0
        qui estadd scalar Mean = r(mean)
        eststo p`lhs'_`event'_noimp
    }
    restore
}

//ES Tables
foreach n in e0 a1 a2 {
    gen `n' = .
}

    label var e0 "Event Wave"
    label var a1 "One Wave After"

foreach lhs in at_pk at_kp {
    estout p`lhs'_wneg2_noimp p`lhs'_wneg2_nonrs  p`lhs'_wshock_nh p`lhs'_wshock_nhf using output/tablec1/`lhs'_post_ws.tex, `NOMEAN_estout' keep(e0 a1) 
}

foreach lhs in any_helpr {
    estout p`lhs'_wneg2_noimp p`lhs'_wneg2_nonrs  p`lhs'_wshock_nh p`lhs'_wshock_nhf using output/tablec1/`lhs'_post_ws.tex, `NOMEAN2_estout' keep(e0 a1) 
    filefilter output/tablec1/`lhs'_post_ws.tex output/tablec1/`lhs'_post2_ws.tex, from("Observations") to ("\BShline Observations") replace
}


//***********************************//
//***********************************//
//***********************************//
/*Allowing Multiple Events*/
//***********************************//
//***********************************//
//***********************************//
/* This is table C7  */
clear
estimates clear

loc events "wneg2 any_rlost_job male_rwidowed fem_rwidowed any_rhosp any_disab any_health3to5 any_rcancr any_rstrok any_rcardiac any_rmemory"
//Estout setup
loc estout "cells(b(fmt(3) star) se(par fmt(3))) mlabels(none) la collabels(,none) eqlabels(none) varwidth(16) modelwidth(12) style(tex) starl(* 0.05 ** .01) rep" 

//***********************************//
//***********************************//
//***********Regressions************//
//***********************************//
//***********************************//
use data/constructed_data/analysisdata.dta, clear
foreach event in wneg2 any_rlost_job male_rwidowed fem_rwidowed any_rhosp any_disab any_health3to5 any_rcancr any_rstrok any_rcardiac any_rmemory {
    di "`event'"
    preserve

    //Setup
    gen temp = 1 if `event'==1 
    bys hhidpn: egen firstevent = min(wave*temp)
    drop temp
    gen eventtime = wave - firstevent 
    gen eventever = firstevent~=.
    keep if eventever==1  

    //Event indicators
    gen b3m = (f3.`event'==1)
    forvalues m = 4/10 {
            replace b3m = 1 if f`m'.`event'==1
        }
    gen b2 = f2.`event'==1
    gen b1 = f1.`event'==1
    gen e0 = `event'==1
    forvalues l = 1/9 {
        gen a`l' = l`l'.`event'==1
    }

//Regressions - Main table
    foreach lhs of varlist at_pk at_kp any_helpr  {
        di "`lhs'"
        qui xtreg `lhs' b3m b2 e0 a1 a2 a3 a4 a5 a6 a7 a8 a9 oldest_age oldest_age2 i.wave [pweight = weight], fe cluster(hhidpn)
        qui estadd scalar Observations = e(N)
        qui estadd scalar Households = e(N_g)
        su `lhs' [weight = weight] if e(sample)==1 & eventtime<0
        qui estadd scalar Mean = r(mean)
            eststo p`lhs'_`event'
        }
    restore
}

gen e0 = .
gen a1 = .
     label var e0 "Event Wave"
     label var a1 "One Wave After"

//Main Outcomes
foreach lhs in at_pk at_kp any_helpr {
    estout p`lhs'_wneg2 p`lhs'_any_rlost_job  p`lhs'_male_rwidowed p`lhs'_fem_rwidowed p`lhs'_any_rhosp p`lhs'_any_disab p`lhs'_any_health3to5 using output/tablec7/`lhs'_post_me.tex, `estout' keep(e0 a1) 
}





